<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >

      <div class="title-container">
        <h3 class="title">铃宇绩效系统</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <i class="el-icon-user-solid"></i>
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <i class="el-icon-lock"></i>
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            autocomplete="on"
			show-password
            @blur="capsTooltip = false"
            @keyup.enter.native="doLoginM('first')"
          />
       
        </el-form-item>
      </el-tooltip>

      <el-button
        :loading="loading"
        type="primary"
		size="medium"
        style="width:100%;margin:20px 0;"
        @click.native.prevent="doLoginM('first')"
      >点击登录</el-button>

    </el-form>

  </div>
</template>

<script>
import loginImg from '@/assets/img/richangbg.png'
import ddLogin from '@/components/DDLogin/dd-login.vue'
import selfCusPermission from '@/store/modules/selfCusPermission.js'
import shopPermission from '@/store/modules/shopPermission.js'
import * as dd from 'dingtalk-jsapi'
export default {
  name: 'Login',
  components: {
    ddLogin
  },
  filters: {},
  data() {
    return {
	  loginRules: {
	    username: [{
	      required: true,
	      trigger: 'blur',
	    }],
	    password: [{
	      required: true,
	      trigger: 'blur',
	    }]
	  },
      loading: false,
      capsTooltip: false,
	  passwordType: 'password',
      loginImg: loginImg,
      loginForm: {
        username: '',
        password: '',
        grant_type: 'password'
      }, // 客户登录
      staffFrom: {
        username: '',
        captcha: '',
        grant_type: 'captcha'
      },
      activeName: 'first',
      TIME_COUNT: 60, // 倒计时时间
      code: '', // 验证码
      show: true, // 控制按钮
      count: '' // 倒数
    }
  },
  computed: {},
  created() {
    let code = this.$route.query.code
    if (code) {
      document.onkeydown = null
      this.activeName = 'second'
    }
    const _self = this
    document.onkeydown = function(e) {
      let key = window.event.keyCode
      if (key === 13) {
        _self.doLoginM(_self.activeName)
      }
    }
		this.ddLogin()
  },
  beforeDestroy() {},
  methods: {
		ddLogin(){
		  if(!dd.version){return false}
			let self = this
			// let parentUrl = document.location.origin + '/xtl-mobile/#/login/login';
			dd.ready(function() {
				dd.runtime.permission.requestAuthCode({
					corpId: 'dingeee8c7b611796dac', // 企业id
					//qtUJu5wwJ90uipP8gwPmN2TZUfuSoI1AMVkDbkJUAhoulWRkOe7bNC4Ezu5W-tPb
					onSuccess: function(info) {
						// alert(info.code)
						// let code =info.code; 
						// _this.$u.toast('钉钉工作台请求错误1' + JSON.stringify(info));
						// _this.$store
						// 	.dispatch('reqOutLogin', { param: { code: info.code, type: 'tripartite' } })
						// 	.then(value => {
						// 		// 登录成功后的逻辑
						// 	})
						// 	.catch(err => {
						// 		_this.$u.toast('钉钉工作台请求错误1' + JSON.stringify(err));
						// 	});
						self.requestLogin({'third_code':info.code,'grant_type':'third_code'})
					},
					onFail: e => {
						self.$u.toast(JSON.stringify(e));
					}
				});
			});
		},
	showPwd() {
	  if (this.passwordType === 'password') {
	    this.passwordType = ''
	  } else {
	    this.passwordType = 'password'
	  }
	  this.$nextTick(() => {
	    this.$refs.password.focus()
	  })
	},
    doLoginM(name) {
      switch (name) {
        case 'first':
          document.onkeydown = null
          this.requestLogin(this.loginForm)
          break
      }
    },
    // 发送验证码
    sendcode() {
      this.getCustomerCode()
    },
    requestLogin(form) {
      this.$http.postEncryption('/ly-code-auth-servicer/oauth/token', form, res => {
        if (Object.values(res).length) {
          if (res.token_type) {
            this.$setLocalItem('jx_access_token', res.access_token)
            this.$setLocalItem('jx_Authorization', 'bearer ' + res.access_token)
            this.$setLocalItem('jx_refresh_token', res.refresh_token)
            this.$setLocalItem('jx_tokenType', res.token_type)
            this.$setLocalItem('jx_nickname', res.nickname)
            this.$setLocalItem('jx_username', res.username)
            this.$setLocalItem('jx_avatar', res.avatar)
            this.getLoginMsg()
            if (res.deptList[0]) {
              this.$setLocalItem('jx_deptId', res.deptList[0].deptId)
              this.$setLocalItem('jx_deptName', res.deptList[0].deptName)
              this.$setLocalItem('jx_deptType', res.deptList[0].deptType)
            }
          }
        }
      })
    },
    getLoginMsg() {
      // 获取权限和菜单树
      Promise.all([this.$store.dispatch('jx_ReqUserMenu'), this.$store.dispatch('jx_ReqUserMsg')]).then(response => {
        const myRes = response[0]
        let path = '/permission'
        if (myRes.code == 0) {
          const data = myRes.data
          if (data.length > 0) {
            path = '/homePage'
          }
        }
        const res = response[1]
        if (res) {
          // 存登录信息
          this.$setLocalItem('jx_RoleCode', res.res.authorities)
          this.$setLocalItem('jx_userinfo', res.res.user_id)
          this.$setLocalItem('jx_nickname', res.res.nickname)
          this.$setLocalItem(
            'pageBtn',
            res.res.authorities.filter(v => v.indexOf('lypc_btn_') > -1)
          )
        }
        this.$goPage({ path: path })
      })
    },
    checkIsNull() {
      let flag = true
      if (!this.loginCodeForm.password) {
        this.$message({
          type: 'error',
          message: '密码不能为空'
        })
        flag = false
      }
      return flag
    },
    getCustomerCode() {
      this.$http.get('/ly-code-auth-servicer/token/captcha?mobile=' + this.staffFrom.username, {}, res => {
        if (res && res.code == 0) {
          this.$message.success('获取验证码成功')
          if (!this.timer) {
            this.count = this.TIME_COUNT
            this.show = false
            this.timer = setInterval(() => {
              console.log('sendcode setInterval1 timer execute')
              if (this.count > 0 && this.count <= this.TIME_COUNT) {
                this.count--
              } else {
                this.show = true
                clearInterval(this.timer) // 清除定时器
                this.timer = null
              }
            }, 1000)
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    doLoginC(json) {
      this.$http.postEncryption('/ly-code-auth-servicer/oauth/token', json, res => {
        if (Object.values(res).length) {
          if (res.token_type) {
            this.$setLocalItem('jx_access_token', res.access_token)
            this.$setLocalItem('jx_Authorization', 'bearer ' + res.access_token)
            this.$setLocalItem('jx_refresh_token', res.refresh_token)
            this.$setLocalItem('jx_nickname', res.nickname)
            this.$setLocalItem('jx_username', res.username)
            this.$setLocalItem('userphone', res.username)
            this.getCustomerPermission()
          }
        }
      })
    },
    getCustomerPermission() {
      Promise.all([this.$store.dispatch('jx_ReqUserMsg')]).then(response => {
        const res = response[0].res
        this.$setLocalItem('jx_userinfo', res.customer.id)
        this.$setLocalItem('isCustomerLogin', true)
        this.$store.commit('SET_ISCUSTOMER', true)
        this.$setLocalItem('customerInfo', res.customer)
        let menu = null
        if (res.customer.type == 'K007') {
          // 如果是专柜
          menu = shopPermission
        } else {
          // 客户自主权限
          menu = selfCusPermission
        }
        this.$store.commit('SET_MENULIST', menu)
        this.$goPage({ path: menu[0].path })
      })
    }
  }
}
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg:#283443;
  $light_gray:#fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }

    }
    .el-radio{
      color: #fff;
    }
    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg:#2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .login-form {
      position: relative;
      width: 420px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }
</style>
